#!usr/bin/env python
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tap_connector06_sqlserver.py
@version:
@time: 2022/01/13 
"""
import pymssql
from pymssql import _mssql
from TapClientConnector.connector.tap_connector00_base import *
from TapClientConnector.connector.tap_connector02_oracle import TAPOracleConnector


class TAPSqlserverConnector(TAPOracleConnector):

    def __init__(self, kwargs):
        super(TAPOracleConnector, self).__init__(kwargs)
        self.connector = pymssql.connect(**self.FORMAT_DB_INFO)
        host = self.FORMAT_DB_INFO.pop('host')
        self.FORMAT_DB_INFO['server'] = host
        self.mssql = _mssql.connect(**self.FORMAT_DB_INFO)

    @connector_query_logger
    def show_tables(self) -> list:
        query_str = "select * from sysobjects where xtype='U' and uid!=5;"
        table_list = []
        query_result = self._query(query_str)
        import asyncio
        async_run = asyncio.get_event_loop().run_until_complete
        table_list = async_run(self.append_table(query_result, table_list))
        return table_list

    @connector_query_logger
    def show_dbs(self) -> list:
        query_str = "select name from sysdatabases;"
        db_list = []
        for i in self._query(query_str):
            db_list.append(i[0])
        return db_list

    @generate_logger
    def generate_table_cdc(self, table):
        return f"""use {self.connector_database};EXEC sys.sp_cdc_enable_table @source_schema=N'{self.connector_schema}', 
        @source_name=N'{table}',@role_name=NULL"""

    @generate_logger
    def generate_db_cdc_query(self):
        return f"SELECT [name], database_id, is_cdc_enabled FROM sys.databases WHERE [name] = N'{self.connector_database}'"

    @connector_exec_logger
    def special_execute(self, sql):
        self.mssql.execute_non_query(sql)
